<template>
	<app-page>
		<wd-config-provider :theme="theme">
			<view class="container" :style="{ height: 'calc(100vh)' }">
				<scroll-view
					:class="['scroll-Y', showUpload ? 'show-upload-list' : '', showBtn([2]) && imType === 'C2C' ? 'in-tips' : '']"
					:scroll-y="true" :scroll-top="scrollTop">
					<!-- 查看更多 -->
					<p v-if="!isCompleted" class="message-more" @click="getHistoryMessageList">查看更多</p>
					<!-- 内容 -->
					<view class="item" v-for="(item, index) in messageList" :id="`tui-${item.ID}`"
						:key="item.vueForRenderKey">
						<MessageTimestamp :currTime="item.time"
							:prevTime="index > 0 ? messageList[index - 1].time : 0" />
						<MessageBubble @resendMessage="resendMessage" :messageItem="item"
							:content="item.getMessageContent()">
							<MessageText v-if="item.type === TYPES.MSG_TEXT" :content="item.getMessageContent()" />
							<ProgressMessage v-if="item.type === TYPES.MSG_IMAGE" :content="item.getMessageContent()"
								:messageItem="item">
								<MessageImage :content="item.getMessageContent()" :messageItem="item"
									@previewImage="handleImagePreview(index)" />
							</ProgressMessage>
							<ProgressMessage v-if="item.type === TYPES.MSG_VIDEO" :content="item.getMessageContent()"
								:messageItem="item">
								<MessageVideo :content="item.getMessageContent()" :messageItem="item" />
							</ProgressMessage>
							<ProgressMessage v-if="item.type === TYPES.MSG_AUDIO" :content="item.getMessageContent()"
								:messageItem="item">
								<MessageAudio :content="item.getMessageContent()" :messageItem="item" />
							</ProgressMessage>
							<MessageOrder :flow="item.flow" :content="item.getMessageContent()"
								v-if="item.type === TYPES.MSG_CUSTOM && item.payload.data === 'order'"></MessageOrder>
						</MessageBubble>
					</view>
				</scroll-view>
				<view :class="['tips', showUpload ? 'show-upload' : '']"
					v-if="platform === 'user' && showBtn([2]) && imType === 'C2C'">
					您购买了电话咨询，如有需要，请点击下方电话图标进行电话咨询。
				</view>
				<view :class="['tips', showUpload ? 'show-upload' : '']"
					v-if="platform !== 'user' && showBtn([2]) && imType === 'C2C'">
					当前用户购买了电话咨询，您可以点击下方电话图标进行电话答疑。
				</view>
				<!-- 输入框 -->
				<view :class="['input-buttom',showUpload ? 'show-upload' : '']" v-if="showBtn() || imType !== 'C2C'">
					<imInput @sendAudioMsg="sendAudioMsg" @setUploadShow="setUploadShow" @sendMsg="sendMsg"></imInput>
				</view>
				<view class="upload-box" v-if="showUpload">
					<view class="item" @click="uploadImg" v-if="showBtn([2, 3]) || imType !== 'C2C'">
						<view class="icon">
							<text class="iconfont icon-tuwenxiangqing"></text>
						</view>
					</view>
					<view class="item" @click="uploadVideo" v-if="showBtn([2, 3]) || imType !== 'C2C'">
						<view class="icon">
							<text class="iconfont icon-shipin1"></text>
						</view>
					</view>
					<view class="item" @click="callPhone" v-if="showBtn([2]) || imType !== 'C2C'">
						<view class="icon">
							<text class="iconfont icon-24gf-phoneBubble"></text>
						</view>
					</view>

					<view class="item" @click="setOrderShow" v-if="platform !== 'user'">
						<view class="icon">
							<text class="iconfont icon-ziyuan"></text>
						</view>
					</view>

					<view class="item" @click="setTailShow" v-if="platform !== 'user'">
						<view class="icon">
							<text class="iconfont icon-ziyuan"></text>
						</view>
					</view>
				</view>
			</view>
		</wd-config-provider>
		<wd-popup safe-area-inset-bottom custom-class="wd-popup-order" v-model="showOrder" position="bottom"
			@close="setOrderShow">
			<view class="body">
				<view class="title">发送订单</view>
				<wd-form ref="form">
					<wd-cell-group border>
						<wd-picker @confirm="pickerConfirm" ref="wdPicker" prop="category_id"
							:column-change="columnChange" v-model="orderInfo.category_id" label-width="100px"
							:columns="caseTypeList" value-key="id" label-key="title" label="案件类型" placeholder="请选择案件类型">
							<template v-slot:default></template>
						</wd-picker>
						<wd-input v-model="orderInfo.price" label="费用" label-width="100px" prop="price" clearable
							placeholder="请输入费用" />
						<wd-cell vertical title-width="100px" title="备注信息">
							<wd-textarea v-model="orderInfo.f_desc" prop="f_desc" on-border auto-height
								placeholder="备注信息" clearable />
						</wd-cell>
					</wd-cell-group>
					<view class="footer">
						<wd-button custom-class="wd-button-custom-class-my-success wd-button-custom-class-w100"
							type="primary" size="large" @click="handleSubmit" block>
							提交
						</wd-button>
					</view>
				</wd-form>
			</view>
		</wd-popup>

		<wd-popup safe-area-inset-bottom custom-class="wd-popup-order" v-model="showTailOrder" position="bottom"
			@close="setTailShow">
			<view class="body">
				<view class="title">发起尾款</view>
				<wd-form ref="form">
					<wd-cell-group border>
						<wd-picker @confirm="pickerCaseConfirm" ref="wdPicker" prop="anjian_order_id"
							v-model="tailOrder.anjian_order_id" label-width="100px" :columns="caseList" value-key="id"
							label-key="anjian_name" label="案件" placeholder="请选择案件">
							<template v-slot:default></template>
						</wd-picker>
						<wd-input v-model="tailOrder.price" label="费用" label-width="100px" prop="price" clearable
							placeholder="请输入费用" />
						<wd-cell vertical title-width="100px" title="备注信息">
							<wd-textarea v-model="tailOrder.remark" prop="remark" on-border auto-height
								placeholder="备注信息" clearable />
						</wd-cell>
					</wd-cell-group>
					<view class="footer">
						<wd-button custom-class="wd-button-custom-class-my-success wd-button-custom-class-w100"
							type="primary" size="large" @click="handleTailSubmit" block>
							提交
						</wd-button>
					</view>
				</wd-form>
			</view>
		</wd-popup>
	</app-page>
</template>

<script lang="ts">
	import { defineComponent, ref, nextTick, computed, watch } from 'vue';
	import { IMessageModel } from '@tencentcloud/chat-uikit-engine';
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import useTencentIm from '../../hooks/useTencentIm';
	import MessageTimestamp from './../components/message-list/message-timestamp.vue';
	import MessageBubble from './../components/message-list/message-bubble.vue';
	import MessageText from './../components/message-list/message-text.vue';
	import MessageImage from './../components/message-list/message-image.vue';
	import MessageVideo from './../components/message-list/message-video.vue';
	import MessageAudio from './../components/message-list/message-audio.vue';
	import ProgressMessage from './../components/message-list/ProgressMessage/index.vue';

	import MessageOrder from './../components/message-list/message-order.vue';
	import imInput from "./../components/im-input.vue"
	import useStatusHeight from '../../hooks/useStatusHeight';
	import useGetDom from '@/im/useGetDom';
	import { useImStore, useUserStore } from '../../store';
	import { getMsg, getUseryPhone, getComOrder as getASKOrderInfoApi, askOrderEnd, getCategoryFirstList, getCategoryTwoList, getProfileByuuid } from '@/api/index';
	import api from '@/api/index';
	import useRouter from '../../hooks/useRouter';

	export default defineComponent({
		name: '',
		components: { MessageTimestamp, MessageBubble, MessageText, MessageImage, MessageVideo, ProgressMessage, MessageOrder, MessageAudio, imInput },
		setup(props, ctx) {
			// 日间light、夜间dark主题
			const theme = ref('light');
			const tencentIM = useTencentIm();
			const statusHeight = useStatusHeight();
			const TYPES = ref(tencentIM.TYPES);
			const imStore = useImStore();
			const userStore = useUserStore();
			// #ifdef MP-WEIXIN
			const getDom = useGetDom();
			// #endif
			// #ifndef MP-WEIXIN
			const getDom = useGetDom(this);
			// #endif
			const router = useRouter();
			const imType = ref('C2C');
			const caseTypeList = ref([]);
			const caseList = ref([]);
			let useruuid = '';
			// 输入框信息
			const msg = ref('');
			// 是否打开更多组件
			const showUpload = ref(false); // 是否显示上传组件，默认不显示，点击加号按钮时显示，再次点击加号按钮时隐藏。
			// 滚动位置
			const scrollTop = ref<number>(0);
			// // 是否第一次执行监听
			// const firstWatch = ref<boolean>(true);
			// 是否打开创建订单
			const showOrder = ref<boolean>(false);
			const showTailOrder = ref<boolean>(false);
			const orderInfo = ref<any>({
				firstCategory: null,
				twoCategory: null,
				category_id: null,
				price: '', // 费用
				f_desc: '' // 备注信息，可不填，用于备注订单信息，如：订单包含xxx商品，不含xxx商品等。
			});
			const tailOrder = ref<any>({
				anjian_order_id: null,
				price: '', // 费用
				remark: '' // 备注信息，可不填，用于备注订单信息，如：订单包含xxx商品，不含xxx商品等。
			});
			const askOrderInfo : any = ref({
				ask_type_id: null,
				expire_time: null,
				id: null,
				order_sn: null,
				price: null
			});

			const getAskOrderInfo = async () => {
				let obj = {};
				if (uni.$appConfig.platform === 'user') {
					obj = {
						user_uuid: userStore.uuid,
						lawyer_uuid: useruuid
						// imStore.currentConversation.userProfile.userID,
					};
				} else {
					obj = {
						user_uuid: useruuid,
						// imStore.currentConversation.userProfile.userID,
						lawyer_uuid: userStore.uuid
					};
				}
				console.log(obj, 'obj');
				try {
					const res = await getASKOrderInfoApi(obj);
					if (res.ask_order.length > 0) {
						askOrderInfo.value = res.ask_order;
					}
					if (res.anjian_order.length > 0) {
						imType.value = 'Case';
						caseList.value = res.anjian_order;
						// askOrderInfo.value = res.ask_order;
					}
				} catch (e) {
					//TODO handle the exception
				} finally {
					// 执行一些清理或收尾操作，无论是否发生异常都会执行到这里。
					setScrollHeight();
				}
			};
			const initCategory = (res : any, func ?: Function) => {
				getCategoryTwoList({
					id: res[0].id
				}).then((res) => {
					if (func) {
						func(res);
					} else {
						orderInfo.value.twoCategory = res[0].id;
						orderInfo.value.category_id = [orderInfo.value.firstCategory, orderInfo.value.twoCategory];
						caseTypeList.value[1] = res;
					}
				});
			};
			const pickerConfirm = (e : any) => {
				console.log(e, 'e');
				if (e.length > 1) {
					orderInfo.value.category_id = e;
				} else {
					// orderInfo.value.category_id = orderInfo.value.twoCategory;
					orderInfo.value.category_id = [orderInfo.value.firstCategory, orderInfo.value.twoCategory];
				}
			};
			const columnChange = (e) => {
				const valuse = e.getValues();
				if (valuse[0] !== orderInfo.value.firstCategory) {
					initCategory(
						[
							{
								id: valuse[0]
							}
						],
						(list) => {
							if (list.length > 0) {
								e.setColumnData(1, list, 0);
								// orderInfo.value.twoCategory = list.id;
								// orderInfo.value.category_id = list.id;
							} else {
								e.setColumnData(1, [e.getSelects()[0]], 0);
								orderInfo.value.twoCategory = e.getSelects()[0].id;
								// orderInfo.value.category_id = list.id;
							}
						}
					);
				}
				orderInfo.value.firstCategory = valuse[0]; // 获取一级分类的值，并将其赋值给orderInfo.firstCategory。
				orderInfo.value.twoCategory = valuse[1]; // 获取二级分类的值，并将其赋值给orderInfo.twoCategory。
				// firstCategory
				// twoCategory
			};

			const pickerCaseConfirm = (e) => {
				console.log(e, 'e');
			};
			const showBtn = (ids = []) => {
				let isOk = false;
				if (askOrderInfo.value.length <= 0 && ids.length <= 0) {
					return false;
				} else if (askOrderInfo.value.length > 0 && ids.length <= 0) {
					return true;
				}
				for (let i = 0; i < askOrderInfo.value.length; i++) {
					let temp = askOrderInfo.value[i];
					if (ids.includes(temp.ask_type_id)) {
						isOk = true;
					}
				}
				return isOk;
			};
			// 设置滚动条位置
			const setScrollHeight = () => {
				nextTick(() => {
					// 滚动到最新一条消息的位置，并触发滚动事件
					try {
						getDom.getDomScroll('.scroll-Y').then((res : any) => {
							if (res && res.scrollHeight) {
								scrollTop.value = res.scrollTop;
								setTimeout(() => {
									scrollTop.value = res.scrollHeight;
								}, 1);
							}
						});
					} catch (e) {
						setTimeout(() => {
							setScrollHeight();
						}, 300);
						console.log(e, 'e');
					}
				});
			};

			// 图片预览
			// 开启图片预览
			const handleImagePreview = (index : number) => {
				if (!messageList) {
					return;
				}
				const imageMessageIndex : number[] = [];
				const imageMessageList : IMessageModel[] = messageList.value.filter((item, index) => {
					if (!item.isRevoked && !item.hasRiskContent && item.type === TYPES.value.MSG_IMAGE) {
						imageMessageIndex.push(index);
						return true;
					}
					return false;
				});
				uni.previewImage({
					current: imageMessageIndex.indexOf(index),
					urls: imageMessageList.map((message) => message.payload.imageInfoArray?.[2].url),
					// #ifdef APP-PLUS
					indicator: 'number'
					// #endif
				});
			};
			// 重新发送
			const resendMessage = (e : any) => {
				imStore.resendMessage(e.value);
			};
			const sendAudioMsg = ({ payload, type }) => {
				imStore.sendMessage(payload, type, useruuid);
				setScrollHeight();
			}
			// 发送信息
			const sendMsg = (text : string) => {
				imStore.sendMessage({ text: text || msg.value }, 'text', useruuid);
				msg.value = '';
				setScrollHeight();
			};
			// 发送图片
			const uploadImg = () => {
				// #ifdef MP-WEIXIN
				uni.chooseMedia({
					count: 1,
					mediaType: ['image'], // 图片
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					success: (res : any) => {
						imStore.sendMessage({ file: res }, 'image', useruuid);
						setUploadShow();
					}
				});
				// #endif
				// #ifndef MP-WEIXIN
				uni.chooseImage({
					count: 1,
					success: (res) => {
						imStore.sendMessage({ file: res }, 'image', useruuid);
						setUploadShow();
					}
				});
				// #endif
			};
			// 发送视频
			const uploadVideo = () => {
				// #ifdef MP-WEIXIN
				uni.chooseMedia({
					mediaType: ['video'], // 视频
					count: 1,
					sourceType: ['album', 'camera'], // album 从相册选视频，camera 使用相机拍摄
					maxDuration: 60, // 设置最长时间60s
					success: (res : any) => {
						imStore.sendMessage({ file: res }, 'video', useruuid);
						setUploadShow();
					}
				});
				// #endif
				// #ifndef MP-WEIXIN
				uni.chooseVideo({
					count: 1,
					sourceType: ['album', 'camera'], // album 从相册选视频，camera 使用相机拍摄
					maxDuration: 60, // 设置最长时间60s
					success: (res) => {
						imStore.sendMessage({ file: res }, 'video', useruuid);
						setUploadShow();
					}
				});
				// #endif
			};
			// 设置更多展示
			const setUploadShow = () => {
				showUpload.value = !showUpload.value;
				setScrollHeight();
			};
			const callPhone = () => {
				uni.$wdToast.confirm('提示', '点击确认后当前会拨打对方电话，请先确认对方是否方便接听').then((res) => {
					getUseryPhone({
						uuid: imStore.currentConversation.userProfile.userID
					}).then((res) => {
						// console.log(res)
						uni.makePhoneCall({
							phoneNumber: res.phone,
							success: () => {
								let temp = askOrderInfo.value.find((item) => item.ask_type_id === 2);
								console.log(temp);
								askOrderEnd({
									ask_order_id: temp.id
								}).then((res) => {
									getAskOrderInfo();
								});
							}
						});
					});
				});
			};

			//
			const setOrderShow = () => {
				showOrder.value = !showOrder.value;
				// 获取案件分类
				getCategoryFirstList().then((res : any) => {
					caseTypeList.value[0] = res;
					orderInfo.value.firstCategory = res[0].id;
					initCategory(res);
				});
				setScrollHeight();
			};
			const setTailShow = () => {
				showTailOrder.value = !showTailOrder.value;
				setScrollHeight();
			};

			const handleSubmit = async () => {
				const userInfo = await getProfileByuuid({
					uuid: useruuid
					// imStore.currentConversation.userProfile.userID
				});
				console.log(uni.$appConfig.platform);
				if (uni.$appConfig.platform === 'user') {
					imStore.sendMessage(
						{
							data: 'order',
							description: '',
							extension: JSON.stringify({
								...orderInfo.value
							})
						},
						'custom',
						useruuid
					);
				} else {
					api.imPubOrder({
						user_id: userInfo.uid,
						...orderInfo.value,
						category_id: orderInfo.value.category_id[1]
					}).then((res : any) => {
						imStore.sendMessage(
							{
								data: 'order',
								description: '',
								extension: JSON.stringify({
									...orderInfo.value,
									orderId: res.order_id
								})
							},
							'custom',
							useruuid
						);
						orderInfo.value = {
							firstCategory: null,
							twoCategory: null,
							category_id: null,
							price: '', // 费用
							f_desc: '' // 备注信息，可不填，用于备注订单信息，如：订单包含xxx商品，不含xxx商品等。
						};
					});
				}

				setUploadShow();
				setOrderShow();
			};
			const handleTailSubmit = async () => {
				const userInfo = await getProfileByuuid({
					uuid: useruuid
					// imStore.currentConversation.userProfile.userID
				});
				console.log(uni.$appConfig.platform);
				if (uni.$appConfig.platform === 'user') {
					imStore.sendMessage(
						{
							data: 'order',
							description: '',
							extension: JSON.stringify({
								...tailOrder.value,
								type: '尾款',
								orderId: tailOrder.value.anjian_order_id
							})
						},
						'custom',
						useruuid
					);
				} else {
					api.pubWeikuanOrder({
						...tailOrder.value
					}).then((res : any) => {
						imStore.sendMessage(
							{
								data: 'order',
								description: '',
								extension: JSON.stringify({
									...tailOrder.value,
									type: '尾款',
									orderId: tailOrder.value.anjian_order_id,
									weikuan_order_id: res.weikuan_order_id
								})
							},
							'custom',
							useruuid
						);
						tailOrder.value = {
							anjian_order_id: null,
							price: '', // 费用
							remark: '' // 备注信息，可不填，用于备注订单信息，如：订单包含xxx商品，不含xxx商品等。
						};
					});
				}

				setUploadShow();
				setTailShow();
			};
			const platform = computed(() => {
				return uni.$appConfig.platform;
			});
			// 从 imStort 获取 信息
			const messageList = computed(() => {
				return imStore.messageList;
			});
			// 从 imStort 获取 信息加载状态
			const isCompleted = computed(() => {
				return imStore.messageList;
			});
			const setNavigationBarTitle = async () => {
				if (imStore.currentConversationID) {
					const res = await imStore.getConversationProfile(imStore.currentConversationID);
					console.log('setNavigationBarTitle', res)
					if (res.code === 0 && res.data.conversation) {
						uni.setNavigationBarTitle({
							title: res.data.conversation.userProfile.nick
						});
					}

				}
			}
			onLoad((params) => {
				if (params.uuid) {
					useruuid = params.uuid;
				} else {
					router.back({
						delta: 1
					});
				}
				console.log(imStore)
				getMsg({
					party_user_id: imStore.friendUid
				}).then(res => {
					console.log(res);
				});
				imStore.watchChat();
				setNavigationBarTitle()
				getAskOrderInfo();
			});

			onShow(() => {
				setTimeout(() => {
					setScrollHeight();
				}, 300);
			});


			return {
				theme,
				TYPES,
				msg,
				showBtn,
				caseTypeList,
				pickerConfirm,
				messageList,
				isCompleted,
				getHistoryMessageList: tencentIM.getHistoryMessageList,
				handleImagePreview,
				sendMsg,
				showUpload,
				setUploadShow,
				uploadImg,
				uploadVideo,
				navHeight: statusHeight.navHeight,
				scrollTop,
				resendMessage,
				showOrder,
				setOrderShow,
				handleSubmit,
				orderInfo,
				callPhone,
				askOrderInfo,
				platform,
				columnChange,
				imType,
				setTailShow,
				showTailOrder,
				tailOrder,
				caseList,
				sendAudioMsg,
				pickerCaseConfirm,
				handleTailSubmit
			};
		}
	});
</script>
<!-- #ifdef MP-WEIXIN -->
<style lang="less">
	page {
		background-color: #f2f2f2;
	}
</style>
<!-- #endif -->
<style lang="less" scoped>
	page {
		background-color: #f2f2f2;
	}

	.wd-popup-order {
		.body {
			padding: 24rpx;

			.wd-cell__value {
				.wd-textarea::after {
					display: none;
				}
			}
		}

		.title {
			font-size: 40rpx;
			font-weight: bold;
			text-align: center;
			padding-bottom: 24rpx;
		}

		.footer {
			margin-top: 24rpx;
		}
	}

	.container {
		height: calc(100%);

		.message-more {
			color: #999;
			cursor: pointer;
			font-size: 14px;
			text-align: center;
			margin-bottom: 24rpx;
		}

		.scroll-Y {
			height: calc(100% - 128rpx - 24rpx);
			padding-top: 24rpx;
		}

		.show-upload-list {
			height: calc(100% - 128rpx - 500rpx);
		}

		.in-tips {
			height: calc(100% - 128rpx - 24rpx - 88rpx);
		}

		.show-upload-list.in-tips {
			height: calc(100% - 128rpx - 500rpx - 88rpx);
		}

		.input-buttom {
			position: fixed;
			bottom: 0;
			width: 100%;
		}

		.tips {
			width: 100%;
			text-align: center;
			font-size: 24rpx;
			color: #fff;
			position: fixed;
			bottom: calc(80rpx + 24rpx + 24rpx);
			padding: 24rpx 0;
			background-color: #c91c1f;
		}



		.show-upload {
			bottom: 500rpx;
		}

		.show-upload.tips {
			bottom: calc(80rpx + 24rpx + 24rpx + 500rpx);
		}

		.upload-box {
			position: fixed;
			bottom: 0rpx;
			height: calc(500rpx - 24rpx - 24rpx);
			padding: 24rpx;
			width: calc(100% - 24rpx - 24rpx);
			background-color: #fff;
			display: flex;
			flex-wrap: wrap;

			.item {
				width: calc(100% / 4);
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				.iconfont {
					font-size: 60rpx;
				}
			}
		}
	}
</style>